import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import ExtraTreesClassifier

# 读取CSV文件
df = pd.read_csv(r'D:\kaggle\final\cancers1.csv')

# 将所有列转换为数值类型
df = df.apply(pd.to_numeric, errors='coerce')

# 删除Number列
df = df.drop(columns=['Number'])

# 舍弃包含缺失值的行
df.dropna(inplace=True)

# 对数据进行范围限制
df['SCC'] = df['SCC'].clip(0, 1.95)
df['CEA'] = df['CEA'].clip(0, 5)
df['CK19'] = df['CK19'].clip(0, 3.3)
df['NSE'] = df['NSE'].clip(0, 17)
df['ProGRP'] = df['ProGRP'].clip(0, 0.1)

# 计算特征重要性
X = df.iloc[:, 0:5]  # 独立变量
y = df.iloc[:, -1]   # 目标变量，即Lung_cancer
model = ExtraTreesClassifier()
model.fit(X, y)
print(model.feature_importances_)  # 使用树模型的内置特征重要性

# 可视化特征重要性
feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(5).plot(kind='barh')
plt.xlabel('Feature Importance')
plt.ylabel('Features')
plt.title('Feature Importance Ranking for Lung Cancer')
plt.show()